package com.hemaapp.yjnh.push;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.activity.BuyerCustomOrderDetailActivity;
import com.hemaapp.yjnh.activity.BuyerOrderDetailActivity;
import com.hemaapp.yjnh.activity.FarmerOrderDetailActivity;
import com.hemaapp.yjnh.activity.FriendPayDetailActivity;
import com.hemaapp.yjnh.activity.LaokeDetailActivity;
import com.hemaapp.yjnh.activity.MainActivity;
import com.hemaapp.yjnh.activity.MyFarmerActivity;
import com.hemaapp.yjnh.activity.NoticeListActivity;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.chat.ChatPrivateActivity;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTTransmitMessage;

import org.json.JSONException;
import org.json.JSONObject;

import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomSharedPreferencesUtil;

/**
 * 继承 GTIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
 * onReceiveMessageData 处理透传消息<br>
 * onReceiveClientId 接收 cid <br>
 * onReceiveOnlineState cid 离线上线通知 <br>
 * onReceiveCommandResult 各种事件处理回执 <br>
 */
public class NoticeIntentService extends GTIntentService {
    private NotificationManager notificationManager = null;

    @Override
    public void onReceiveServicePid(Context context, int pid) {
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        Log.d(TAG, "onReceiveMessageData -> " + "msg = " + msg);
        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();

        // 第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
        boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);

        if (payload != null) {
            String data = new String(payload);

            String msg_content = "";
            String msg_keytype = "";
            String msg_keyid="";
            String msg_nickname = "";
            String msg_avatar = "";
            try {
                JSONObject msgJson = new JSONObject(data);
                msg_keytype = msgJson.getString("keyType");
                msg_keyid = msgJson.getString("keyId");
                msg_content = msgJson.getString("msg");
                msg_nickname = msgJson.getString("nickname");
                msg_avatar = msgJson.getString("avatar");
            } catch (JSONException e) {
                return;
            }
            if (msg_nickname == null || TextUtils.isEmpty(msg_nickname))
                msg_nickname = "易家农户";
            showNotification(context, msg_content, msg_nickname, msg_keytype, msg_keyid);
        }
    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        Log.d(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
        XtomSharedPreferencesUtil.save(context, "clientid", clientid);
        PushUtils.saveUserId(context, clientid);
        PushUtils.saveChannelId(context, clientid);
        EventBusMsg msg = new EventBusMsg();
        msg.setType(EventBusConfig.PUSH_CID);
        EventBus.getDefault().post(msg);
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
    }

    public void showNotification(Context context, String content, String title,
                                 String keytype, String keyid) {
        Intent intent;
        //keytype:
        //	0：真聊天消息
        //	1：系统通知
        //2：帖子回复（帖子代指项目核心业务模型）
        //3：简单聊天（假聊天）
        //5：申请好友
        //6：卖家普通订单通知
        //7：代付订单通知
        //8：买家普通订单通知
        //9：买家定制订单通知；
        //10：卖家定制订单通知；
        //11：冻结用户通知
        if ("1".equals(keytype)) {
            intent = new Intent(context, NoticeListActivity.class);
            intent.putExtra("start", 2);
        }else if ("2".equals(keytype)) {
            intent = new Intent(context, LaokeDetailActivity.class);
            intent.putExtra("blog_id", keyid);
        }else if ("0".equals(keytype)) {//跳转到聊天界面
            if (BaseUtil.isChatRunning(context))
                return;
//			intent = new Intent(context, ChatPrivateActivity.class);
//			intent.putExtra("to_client_id", keyid);
            intent = new Intent(context, NoticeListActivity.class);
        }else if ("6".equals(keytype)) {//跳转SellerOrderDtlActivity卖家订单详情
            intent = new Intent(context, FarmerOrderDetailActivity.class);
            intent.putExtra("order_id", keyid);
        }else if ("7".equals(keytype)) {//跳转FriendPayDtlActivity申请方和被申请方的代付
            intent = new Intent(context, FriendPayDetailActivity.class);
            intent.putExtra("order_id", keyid);
        }else if ("8".equals(keytype)) {//跳转BuyerOrderDtlActivity买家订单详情
            intent = new Intent(context, BuyerOrderDetailActivity.class);
            intent.putExtra("order_id", keyid);
        }else if ("9".equals(keytype)) {//9：买家定制订单通知
            intent = new Intent(context, BuyerCustomOrderDetailActivity.class);
            intent.putExtra("order_id", keyid);
        }else if ("10".equals(keytype)) {//卖家定制订单通知,
            User user = BaseApplication.getInstance().getUser();
            if (user != null && user.getRole().equals("1")) {//如果是田家
                intent = new Intent(context, MyFarmerActivity.class);
                intent.putExtra("start_page", 2);
            }else {
                return;
            }
        }else {
            intent = new Intent(context, MainActivity.class);
        }
        intent.putExtra("msgshow", true);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //设置显示Notification
        if (notificationManager == null)
            notificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher));
        builder.setTicker(content);
        builder.setContentTitle(title);
//        builder.setContentInfo(content);
        builder.setContentText(content);
        builder.setContentIntent(contentIntent);
        builder.setWhen(System.currentTimeMillis());
        builder.setAutoCancel(true);//true点击后消息，false只能滑动删除
        builder.setDefaults(Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND);
        notificationManager.notify(0, builder.build());
    }
}
